package com.daxt.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.apache.commons.lang3.StringUtils;

/**
 * 时间工具类 所有跟时间相关的工具集合
 * 
 * @author Ethen
 *
 */
public class DateUtil {

	/**
	 * 时间格式
	 * 
	 * @author kinfer
	 *
	 */
	public enum DateFormat {
		YYYY_MM_DD_HH_mm_ss("yyyy-MM-dd HH:mm:ss"), 
		YYYY_MM_DD_H_mm("yyyy-MM-dd H:mm"), 
		YYYY_MM_DD_HH("yyyy-MM-dd HH"), 
		YYYYMMDDHHMMSS("yyyyMMddHHmmss"), 
		YYYYMMDDHHMMCHINESE("yyyy年MM月dd日 HH:mm"), 
		YYYYMMDDCHINESE("yyyy年MM月dd日"), 
		YYYY_MM_DD("yyyy-MM-dd"),
		YYYY1MM1DD("yyyy.MM.dd"),
		YYYYXMMXDD("yyyy/MM/dd"), 
		HH_mm_ss("HH:mm:ss"), 
		HH_mm("HH:mm"), 
		YYYY_MM("yyyy-MM"), 
		MM_DD("MM-dd"), 
		YYYY("yyyy"), 
		YYYYMMDD("yyyyMMdd"),
		MM("MM"), 
		DD("dd");

		private String value;

		DateFormat(String value) {
			this.value = value;
		}

		public String getValue() {
			return this.value;
		}
	}
	
	/**
	 * 当前时间
	 * 
	 * @param format
	 * @return
	 */
	public static String getCurrentTime() {

		Date date = new Date();// 当前日期
		SimpleDateFormat sdf = new SimpleDateFormat(DateFormat.YYYY_MM_DD_HH_mm_ss.getValue());// 格式化对象
		return sdf.format(date);
	}

	/**
	 * 当前时间
	 * 
	 * @param format
	 * @return
	 */
	public static String getCurrentTime(DateFormat format) {

		Date date = new Date();// 当前日期
		SimpleDateFormat sdf = new SimpleDateFormat(format.getValue());// 格式化对象
		return sdf.format(date);
	}

	/**
	 * 格式化指定日期
	 *
	 * @param format
	 * @return
	 */
	public static String getFormatDate(Date date ,DateFormat format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format.getValue());// 格式化对象
		return sdf.format(date);
	}

	
	/**
	 * 获取几小时前的时间
	 * @param hour
	 * @param dateFormat
	 * @return
	 */
	public static String beforeHourTime(int hour, DateFormat dateFormat) {

		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - hour); // 把时间设置为当前时间-1小时，同理，也可以设置其他时间

		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat.getValue());// 格式化对象
		return sdf.format(cal.getTime());
	}
	
	/**
	 * 格式化时间
	 * 
	 * @param format
	 * @return
	 */
	public static String getFormatTime(String time, DateFormat sourceFormat, DateFormat targetFormat) {

		if (time == null || time.equals("")) {
			return "";
		}
		if (targetFormat == null) {
			return time;
		}
		SimpleDateFormat sdf = new SimpleDateFormat(sourceFormat.getValue());// 格式化对象

		Date date = null;
		try {
			date = sdf.parse(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date != null ? new SimpleDateFormat(targetFormat.getValue()).format(date) : time;
	}

	/**
	 * 时间相减 开始时间 paramSystemTime 系统时间
	 * 
	 * @return 时间相减工具方法 Second(秒)
	 */
	public static int timeSubtractionSecond(String startTime, String endTime) {
		return timeSubtractionSecond(startTime, endTime, DateFormat.YYYY_MM_DD_HH_mm_ss);
	}

	/**
	 * 时间相减 开始时间 paramSystemTime 系统时间
	 * 
	 * @param startTime
	 * @param endTime
	 * @param dateFormat
	 * @return
	 */
	public static int timeSubtractionSecond(String startTime, String endTime, DateFormat dateFormat) {
		int resultTime = 0;// 结果时间
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat.getValue());// 格式化对象
		Calendar calSystem = Calendar.getInstance();// 系统时间
		Calendar calStart = Calendar.getInstance();// 开始时间
		try {
			calSystem.setTime(sdf.parse(startTime));
			calStart.setTime(sdf.parse(endTime));
			long l = calStart.getTimeInMillis() - calSystem.getTimeInMillis();
			Long a=l/1000;
			resultTime = a.intValue();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultTime;
	}

	/**
	 * 时间相差天数
	 * 
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static int betweenDays(String startTime, String endTime) {
		return betweenDays(startTime, endTime, DateFormat.YYYY_MM_DD_HH_mm_ss);
	}

	/**
	 * 时间相差天数
	 * 
	 * @param startTime
	 * @param endTime
	 * @param dateFormat
	 * @return
	 */
	public static int betweenDays(String startTime, String endTime, DateFormat dateFormat) {
		int seconds = timeSubtractionSecond(startTime, endTime, dateFormat);
		return seconds / 60 / 60 / 24;
	}
	
	/**
	 * T+1计息期限
	 * 
	 * @param currentDate
	 *            y-m-d
	 * @param repayDate
	 *            y-m-d
	 * @return
	 */
	public static int tradeDuration(String currentDate, String repayDate) {
		String startDate = addDayOfMonth(currentDate, DateFormat.YYYY_MM_DD, 1);
		return betweenDays(startDate, repayDate, DateFormat.YYYY_MM_DD);
	}

	/**
	 * 在日期上减去天数
	 * 
	 * @param date
	 * @param dateFormat
	 * @param numDay
	 * @return
	 */
	public static String subDayOfMonth(String date, DateFormat dateFormat, int numDay) {

		SimpleDateFormat df = new SimpleDateFormat(dateFormat.getValue());
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(df.parse(date));
			c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - numDay);

			return df.format(c.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
			System.err.print(e);
			return null;
		}
	}

	/**
	 * 日期加上天数
	 * 
	 * @param date
	 * @param dateFormat
	 * @param numDay
	 * @return
	 */
	public static String addDayOfMonth(String date, DateFormat dateFormat, int numDay) {

		SimpleDateFormat df = new SimpleDateFormat(dateFormat.getValue());
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(df.parse(date));
			c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + numDay);

			return df.format(c.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
			System.err.print(e);
			return null;
		}
	}

	/**
	 * 日期减月数
	 * 
	 * @param date
	 * @param dateFormat
	 * @param monthNum
	 * @return
	 */
	public static String subMonth(String date, DateFormat dateFormat, int monthNum) {

		SimpleDateFormat df = new SimpleDateFormat(dateFormat.getValue());
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(df.parse(date));
			c.set(Calendar.MONTH, c.get(Calendar.MONTH) - monthNum);

			return df.format(c.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
			System.err.print(e);
			return null;
		}
	}

	/**
	 * 日期加上月数
	 * 
	 * @param date
	 * @param dateFormat
	 * @param monthNum
	 * @return
	 */
	public static String addMonth(String date, DateFormat dateFormat, int monthNum) {

		SimpleDateFormat df = new SimpleDateFormat(dateFormat.getValue());
		Calendar c = Calendar.getInstance();
		try {
			c.setTime(df.parse(date));
			c.set(Calendar.MONTH, c.get(Calendar.MONTH) + monthNum);

			return df.format(c.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
			System.err.print(e);
			return null;
		}
	}

	/**
	 * 在日期上减去天数, 返回 月数
	 * 
	 * @param date
	 * @param dateFormat
	 * @param numDay
	 * @return
	 * @throws ParseException
	 */
	public static int subDayOfMonthNum(String date, DateFormat dateFormat, int numDay) throws ParseException {

		SimpleDateFormat df = new SimpleDateFormat(dateFormat.getValue());
		Calendar c = Calendar.getInstance();
		c.setTime(df.parse(date));
		c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - numDay);
		String month = new SimpleDateFormat("MM").format(date);

		return Integer.parseInt(month);
	}
	
	/**
	 * 格式化显示两个时间差
	 * X天X时X分
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static String formatDateShow(String startTime, String endTime){
		
		int totalSeconds = timeSubtractionSecond(startTime, endTime);
		
		int day = totalSeconds / (60 * 60 * 24);
		int hour = totalSeconds /(60 * 60) % 24;
		int minute = totalSeconds / 60 - (day * 24 * 60) - (hour * 60);
		
		StringBuilder builder = new StringBuilder();
		
		if(day > 0){
			
			builder.append(day).append("天");
		}
		
		if(hour > 0){
			
			builder.append(hour).append("时");
		}
		
		if(minute < 0){
			
			minute = 0;
		}
		
		builder.append(minute).append("分");
		
		return builder.toString();
	}
	/** 
	 * 取得某月天数 
	 * */
	public static int getCurrentMonthLastDay(Date date){
		Calendar a = Calendar.getInstance();
		a.setTime(date);
		return a.getActualMaximum(Calendar.DAY_OF_MONTH);
		}
	
	public static String replaceStr(String time){
		if(StringUtils.isNotBlank(time)) {
			int indexOf = time.indexOf(".");
			if(indexOf>-1) {
				String newStr = time.substring(0,indexOf).replace("T", " ");
				String newTime=StringUtils.countMatches(newStr, ":")>1?newStr.substring(0,newStr.lastIndexOf(":")):newStr; 
				DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
				LocalDateTime parse = LocalDateTime.parse(newTime,dateTimeFormatter);
				parse.plusHours(8);
				return dateTimeFormatter.format(parse); 
			}
		}
		return time;
		
	}


	/**
	 * @description: 将时间戳转换为时间
	 *
	 * @author: lig
	 * @date: 2022/8/18
	 */
	public static String stampToTime(String str){
		String res;

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.SHORT_IDS.get("CTT")));
		long lt = new Long(str);
		//将时间戳转换为时间
		Date date = new Date(lt);
		//将时间调整为yyyy-MM-dd HH:mm:ss时间样式
		res = simpleDateFormat.format(date);
		return res;
	}

	/**
	 * @description: 时间字符串中获取年份
	 *
	 * @author: lig
	 * @date: 2022/8/18
	 */
	public static String getYear(String date){
		String year= date.substring(0,date.indexOf("-"));
		return year;
	}


	/**
	 * @description: 返回时间格式如：2022-02-17 00:00:00
	 *
	 * @author: lig
	 * @date: 2022/8/23
	 */
	public static String getStartOfDay(Date time) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
	}
	/**
	 * @description: 返回时间格式如：2022-02-19 23:59:59
	 *
	 * @author: lig
	 * @date: 2022/8/23
	 */
	public static String getEndOfDay(Date time) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(time);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
	}


	/*public static void main(String[] args) {
		//String fileName="sssa（asasa）.jahg";
		//StringBuilder s=new StringBuilder(fileName);
		//fileName=s.replace(s.indexOf("（"),s.lastIndexOf("）")+1,"").toString();
		//System.out.println(fileName);


		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		System.out.println(year);
	}*/
}
